package problems.painteddesert;

import java.util.ArrayList;
import java.util.List;

public class World {
	public static final int EMPTY = 0;
	int[][] _world;
	private int _height;
	private int _width;
	private List<Ant> _ants;

	public World(int[][] world) {
		_height = world.length;
		_width = world[0].length;
		_world = new int[_height][_width];
		for (int i = 0; i < _height; i++) {
			System.arraycopy(world[i], 0, _world[i], 0, _width);
		}
		_ants = new ArrayList<Ant>();

	}

	public World(int width, int height, int num_colors, int num_grains) {
		// new world array
		_world = new int[width][height];
		_ants = new ArrayList<Ant>();
		_height = height;
		_width = width;

		// randomly place the sands
		for (int i = 0; i < num_grains; i++) {
			int x = (int) (Math.random() * width);
			int y = (int) (Math.random() * height);

			// if its an empty spot pick a random color
			if (_world[y][x] == 0) {
				_world[y][x] = (int) (Math.random() * (num_colors + 1));
			}
			// it wasn't empty, so we need to try again.
			else {
				i--;
			}
		}
	}

	public void addAnt(Ant ant) {
		_ants.add(ant);
		ant.setWorld(this);
	}

	public int getColor(int x, int y) {
		return _world[y][x];
	}

	public int getHeight() {
		return _height;
	}

	public int getWidth() {
		return _width;
	}

	public void setColor(int x, int y, int color) {
		_world[y][x] = color;
	}

	public String toString() {
		StringBuilder str = new StringBuilder();

		for (int y = 0; y < getHeight(); y++) {
			for (int x = 0; x < getWidth(); x++) {
				if (getColor(x, y) > 0) {
					str.append(getColor(x, y));
				} else {
					boolean found_ant = false;
					for (Ant ant : _ants) {
						if (ant.getX() == x && ant.getY() == y) {
							if (ant.getCarryingColor() > 0) {
								str.append('O');
							} else {
								str.append('x');
							}
							found_ant = true;
							break;
						}
					}

					if (!found_ant) {
						str.append(' ');
					}
				}
			}
			str.append('\n');
		}

		return str.toString();
	}

	public void step() {
		for (Ant ant : _ants) {
			ant.step();
		}
	}

	int[][] getWorld() {
		return _world;
	}
}
